<?php

//error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.message.message_explain");
\ns_core\m_load::load("ns_core.m_pinyin");
\ns_core\m_load::load("ns_core.m_config");

class message extends \ns_model\message\message_explain
{
    private $msg_id = '';
    private $source_id = '';

    private $view_type = array(
        '0' => array('电影'),
        '1' => array('电视剧'),
        '3' => array('动漫'),
        '4' => array('音乐','卡拉OK'),//音乐
        '5' => array('历史地理'),//纪实
        '6' => array('中育'),//教育
        '8' => array('休闲娱乐'),//生活
        '9' => array('经济'),//财经
        '12' => array('广告'),//广告
        '13' => array('新闻'),//新闻
        '23' => array('政治'),
        '24' => array('军事'),
        '25' => array('法律'),
        '26' => array('文教卫生体育'),
        '27' => array('文艺'),
        '28' => array('科技人文'),
        '29' => array('其他'),
        '30' => array('舞蹈'),
        '31' => array('三农'),
    );
    private $except_plateform = array('OTT');//不获取哪一个平台的数据

    public function explain($message)
    {
        \ns_core\m_load::load_np("np_xml_to_array.class.php");

        $this->msg_id = $message['nns_message_id'];
        $this->source_id = $message['nns_cp_id'];

        $content = $this->get_message_content($message);
        if($content['ret'] != NS_CDS_SUCCE || strlen($content['data_info']) < 1)
        {
            \m_config::write_message_execute_log("消息接收成功,注入失败，消息ID[{$message['nns_message_id']}]" . $content['reason'],$this->source_id);
            return $content;
        }
        $str_content = \m_config::trim_xml_header($content['data_info']);
        if(!m_config::is_xml($str_content))
        {
            \m_config::write_message_execute_log("消息接收成功,注入失败,消息ID[{$message['nns_message_id']}]xml内容非xml结构",$this->source_id);
            return \m_config::return_data(NS_CDS_FAIL,"消息ID[{$message['nns_message_id']}]xml内容非xml结构");
        }
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($str_content);
        $xml = $dom->saveXML();
        $xml_content = $this->xml_to_array($xml);
        if(!is_array($xml_content))
        {
            \m_config::write_message_execute_log("消息接收成功,注入失败,消息ID[{$message['nns_message_id']}],解析得到的媒资元数据错误",$this->source_id);
            return \m_config::return_data(NS_CDS_FAIL, "解析得到的媒资元数据错误");
        }
        //初始化主媒资、分集、片源、海报内容
        $vod_info = array();
        $index_info = array();
        $media_info = array();
        $img = array();

        //package层信息
        $package_arr = $xml_content['Metadata'];
        //title层信息
        $title_arr = $xml_content['Asset']['Metadata'];
        //movie与poster层信息
        $other_arr = $xml_content['Asset']['Asset'];
        if(key_exists('Metadata', $other_arr))
        {
            $meta_data = array($other_arr);
        }
        else
        {
            $meta_data = $other_arr;
        }
        //获取主媒资其余信息与分集信息
        //add begin
        //修改、添加
        //组装主媒资、分集信息
        $build_result = $this->build_video_index_info($package_arr,$title_arr);
        if($build_result === false)
        {
            \m_config::write_message_execute_log("消息接收成功,解析失败,消息ID[{$message['nns_message_id']}],解析数组并组装主媒资、分集信息内部错误",$this->source_id);
            return \m_config::return_data(NS_CDS_FAIL, "解析数组并组装主媒资、分集信息发生内部错误");
        }
        $vod_info = $build_result['vod'];
        $index_info = $build_result['index'];
        //分集注入ID
        $index_info['asset_id'] = $vod_info['originalid'];

        //片源、海报信息
        foreach ($meta_data as $value)
        {
            //片源，可能会存在多个
            $medias = array();
            if($value['Metadata']['AMS']['@attributes']['Asset_Class'] === 'movie')
            {
                if(!is_array($value['Metadata']['App_Data']))
                {
                    continue;
                }
                foreach ($value['Metadata']['App_Data'] as $media)
                {
                    switch ($media['@attributes']['Name'])
                    {
                        case 'Asset_Profile':
                            $medias['video_type'] = strtolower($media['@attributes']['Value']);
                            if(empty($media['@attributes']['Value']))
                            {
                                $medias['video_type'] = 'std';
                            }
                            break;
                        case 'Content_FileSize':
                            $medias['file_size'] = empty($media['@attributes']['Value']) ? 1 : $media['@attributes']['Value'];
                            break;
                        case 'FileFormat':
                            $medias['file_type'] = 'ts';
                            break;
                        case 'Bit_Rate':
                            $medias['bitrate'] = $media['@attributes']['Value'];
                            break;
                        case 'Run_Time':
                            $medias['time_len'] = strtotime($media['@attributes']['Value'])-strtotime(date('Y-m-d'));
                            break;
                        case 'Asset_Tag':
                            $medias['Platform'] = $media['@attributes']['Value'];
                            break;
                        case 'Content_Id':
                            $medias['file_core_id'] = $media['@attributes']['Value'];
                            break;
                    }

                }
                $medias['originalid'] = $value['Metadata']['AMS']['@attributes']['Asset_ID'];
                $medias['file_name'] = $value['Metadata']['AMS']['@attributes']['Asset_Name'];
                $medias['path'] = $value['Content']['@attributes']['Value'];
                $medias['clip_id'] = $index_info['originalid'];
                $medias['asset_id'] = $vod_info['originalid'];
                $movie_info[] = $value['Metadata']['AMS']['@attributes']['Asset_ID'];
                $media_info[] = $medias;
            }
            //海报可能会存在多个
            $poster = array();
            if($value['Metadata']['AMS']['@attributes']['Asset_Class'] === 'poster')
            {
                if(!is_array($value['Metadata']['App_Data']))
                {
                    continue;
                }
                foreach ($value['Metadata']['App_Data'] as $picture)
                {
                    switch ($picture['@attributes']['Name'])
                    {
                        case 'Image_Aspect_Ratio':
                            $poster['Image_Aspect_Ratio'] = $picture['@attributes']['Value'];
                            break;
                    }
                }
                $poster['path'] = $value['Content']['@attributes']['Value'];
                $poster['pic_id'] = $value['Metadata']['AMS']['@attributes']['Asset_ID'];
                $img[] = $poster;
            }
        }
        //筛选片源
        if(!empty($media_info))
        {
            foreach($media_info as $key=>$info)
            {
                if(in_array($info['Platform'], $this->except_plateform))
                {
                    unset($media_info[$key]);
                    continue;
                }
                $media_info[$key]['path'] = $info['path'];
            }
            shuffle($media_info);
        }
        //筛选海报
        if(!empty($img))
        {
            $pic = $img[0];
            //获取第一集的图片作为主媒资的图片
            if(!empty($index_info) && intval($index_info['index']) === 0)
            {
                $vod_info['pic'] = $pic['path'];
            }
            $index_info['pic'] = $pic['path'];
        }

        $result = $this->video($vod_info);
        if($result['ret'] == NS_CDS_SUCCE)
        {
            $result = $this->index($index_info);
            if($result['ret'] == NS_CDS_SUCCE && !empty($media_info))
            {
                $result = $this->media($media_info);
            }
        }
        \m_config::write_message_execute_log("消息接收成功,消息ID[{$message['nns_message_id']}]队列生成结果：" . $result['reason'],$this->source_id);
        return $result;
    }

    /**
     * 主媒资注入
     * @param $arr_movie
     * @return array|multitype
     */
    private function video($val_series)
    {

        $do_category = array(
            'base_info'=>array(
                'nns_name' => $val_series['assets_category'],   //栏目名称支持多层目录，多层目录的时候 /分割
                'nns_import_category_id' => '', //栏目名称支持多层目录，多层目录的时候 /分割
                'nns_cp_id' => $this->source_id,
                'nns_import_parent_category_id' => '',
                'nns_video_type' => '0',  //媒资类型  0 点播 | 1 直播
            ),
        );
        $result = $this->category_action('add', $do_category);
        if($result['ret'] != NS_CDS_SUCCE)
        {
            \m_config::write_message_execute_log("消息接收成功,注入失败,消息ID[{$this->msg_id}],原因：" . $result['reason'],$this->source_id);
            return $result;
        }
        if(!isset($result['data_info']['base_info']['nns_id']) || strlen($result['data_info']['base_info']['nns_id']) < 1)
        {
            \m_config::write_message_execute_log("消息接收成功,注入失败,消息ID[{$this->msg_id}],原因创建栏目失败：" . $result['reason'],$this->source_id);
            return \m_config::return_data(NS_CDS_FAIL,'创建栏目失败');
        }
        $nns_category_id = $result['data_info']['base_info']['nns_id'];

        $add_series = array(
            'base_info' => array(
                'nns_name' => $val_series['name'],
                'nns_view_type' => $val_series['view_type'],
                'nns_org_type' => '0',
                'nns_tag' => '26,',
                'nns_director' => $val_series['director'],
                'nns_actor' => $val_series['actor'],
                'nns_show_time' =>  $val_series['release_time'],
                'nns_view_len' => 0,
                'nns_all_index' => intval($val_series['totalnum']) === 0 ? 1 : intval($val_series['totalnum']),
                'nns_new_index' => 0,
                'nns_area' => $val_series['national'],
                'nns_image0' => '',
                'nns_image1' => '',
                'nns_image2' => isset($val_series['pic']) ? $val_series['pic'] : '',
                'nns_image3' => '',
                'nns_image4' => '',
                'nns_image5' => '',
                'nns_summary' => $val_series['summary'],
                'nns_remark' => '',
                'nns_category_id' => $nns_category_id,
                'nns_play_count' => '0',
                'nns_score_total' => '0',
                'nns_score_count' => '0',
                'nns_point' => '0',
                'nns_copyright_date' => '',
                'nns_asset_import_id' => $val_series['originalid'],
                'nns_pinyin' => '',
                'nns_pinyin_length' => '',
                'nns_alias_name' => '',
                'nns_eng_name' => '',
                'nns_language' => $val_series['language'],
                'nns_text_lang' => '',
                'nns_producer' => $val_series['provider_id'],
                'nns_screenwriter' => '',
                'nns_play_role' => '',
                'nns_copyright_begin_date' => '',
                'nns_copyright_range' => '',
                'nns_vod_part' => '',
                'nns_keyword' => $val_series['sreach_key'],
                'nns_import_source' => evn::get("project"),
                'nns_kind' => $val_series['tag'],
                'nns_copyright' => '',
                'nns_clarity' => '',
                'nns_image_v' => isset($val_series['pic']) ? $val_series['pic'] : '',
                'nns_image_s' => '',
                'nns_image_h' => '',
                'nns_cp_id' => $this->source_id,
                'nns_conf_info' => '',
                'nns_ext_url' => '',
            ), //基本信息（存储于nns_vod表中）
            'ex_info' => array(
                'svc_item_id' => '',
                'month_clicks' => '',
                'week_clicks' => '',
                'base_id' => '',
                'asset_path' => '',
                'ex_tag' => '',
                'full_spell' => '',
                'awards' => '',
                'year' => $val_series['year'],
                'play_time' => '',
                'channel' => '',
                'first_spell' => '',
                'online_identify' => $val_series['online_identify'],
            ), //扩展信息（存储于nns_vod_ex表中）
        );
        return $this->vod_action('add', $add_series);
    }

    /**
     * 分集注入
     * @param $val_program
     * @return array|multitype
     */
    private function index($val_program)
    {
        $add_index = array(
            'base_info' => array(
                'nns_name' => $val_program['name'],
                'nns_index' => $val_program['index'],
                'nns_time_len' => $val_program['time_len'],
                'nns_summary' => $val_program['summary'],
                'nns_image' => $val_program['pic'],
                'nns_play_count' => 0,
                'nns_score_total' => 0,
                'nns_score_count' => 0,
                'nns_video_import_id' => $val_program['asset_id'],
                'nns_import_id' => $val_program['originalid'],
                'nns_import_source' => evn::get("project"),
                'nns_director' => $val_program['director'],
                'nns_actor' =>$val_program['actor'],
                'nns_release_time' => $val_program['release_time'],
                'nns_update_time' => date("Y-m-d"),
                'nns_watch_focus' => '',
                'nns_cp_id' => $this->source_id,
                'nns_conf_info' => '',
                'nns_ext_url' => '',
            ),
            'ex_info' => array(
                'isintact' => '',
                'subordinate_name' => '',
                'initials' => '',
                'publisher' => '',
                'first_spell' => '',
                'caption_language' => '',
                'language' => $val_program['language'],
                'region' => $val_program['national'],
                'adaptor' => '',
                'sreach_key' => '',
                'event_tag' => '',
                'year' => $val_program['year'],
                'sort_name' => '',
            ),
        );
        return $this->index_action('add', $add_index);
    }

    /**
     * 片源注入
     * @param $arr_movie
     * @return array|multitype
     */
    private function media($arr_movie)
    {
        foreach ($arr_movie as $val_movie)
        {
            //片源参数
            $add_media = array(
                'base_info' => array(
                    'nns_name' => $val_movie['file_name'],
                    'nns_type' => 1,
                    'nns_url' => $val_movie['path'],
                    'nns_tag' => '26,',
                    'nns_mode' => strtolower($val_movie['video_type']),
                    'nns_kbps' => '',
                    'nns_content_id ' => $val_movie['file_core_id'],
                    'nns_content_state' => 0,
                    'nns_filetype' => empty($val_movie['file_type']) ? 'ts' : $val_movie['file_type'],
                    'nns_play_count' => '0',
                    'nns_score_total' => '0',
                    'nns_score_count' => '0',
                    'nns_video_import_id' => $val_movie['asset_id'],
                    'nns_index_import_id' => $val_movie['clip_id'],
                    'nns_import_id' => $val_movie['originalid'],
                    'nns_import_source' => evn::get("project"),
                    'nns_dimensions' => '2D',
                    'nns_ext_url' => '',
                    'nns_file_size' => empty($val_movie['file_size']) ? 1 : $val_movie['file_size'],
                    'nns_file_time_len' => $val_movie['time_len'],
                    'nns_file_frame_rate' => 0,
                    'nns_file_resolution' => '',
                    'nns_cp_id' => $this->source_id,
                    'nns_ext_info' => '',
                    'nns_drm_enabled' => $val_movie['Encrypted'],
                    'nns_drm_encrypt_solution' =>  '',
                    'nns_drm_ext_info' => '',
                    'nns_domain' => 0,
                    'nns_media_type' => 1,
                    'nns_original_live_id' => '',
                    'nns_start_time' => '',
                    'nns_media_service' => 'HTTP',
                    'nns_conf_info' => '',
                    'nns_encode_flag' =>0,
                    'nns_live_to_media' => '',
                    'nns_media_service_type' => '',
                ),
                'ex_info' => array(
                    'file_hash' => '',
                    'file_width' => '',
                    'file_height' => '',
                    'file_scale' => '',
                    'file_coding' => '',
                ),
            );
            $result = $this->media_action('add', $add_media);
        }
        return $result;
    }
    /**
     * 组装主媒资、分集信息
     */
    private function build_video_index_info($package,$title)
    {
        if(!is_array($package) || !is_array($title) || empty($package) || empty($title))
        {
            return false;
        }
        $vod = array();
        $index = array();
        //获取主媒资信息
        foreach ($package as $key=>$val)
        {
            switch ($key)
            {
                case 'AMS':
                    $vod['originalid'] = $val['@attributes']['Asset_ID'];
                    $vod['provider'] = $val['@attributes']['Provider'];
                    $vod['provider_id'] = $val['@attributes']['Provider_ID'];
                    $vod['name'] = $val['@attributes']['Asset_Name'];
                    break;
                case 'App_Data':
                    if(is_array($val))
                    {
                        foreach ($val as $v)
                        {
                            switch ($v['@attributes']['Name'])
                            {
                                case 'Genre':
                                    $vod['tag'] = str_replace(array(",", " ", "/", "\\", "-", "_",";",'，'), '|',$v['@attributes']['Value']);
                                    break;
                                case 'Keyword':
                                    $vod['sreach_key'] = str_replace(array(",", " ", "/", "\\", "-", "_",";",'，'), '|',$v['@attributes']['Value']);
                                    break;
//     							case 'Classify':
//     								$vod['assets_category'] = empty($v['@attributes']['Value']) ? '电影' : $v['@attributes']['Value'];
//     							break;
                                case 'Year':
                                    if(empty($v['@attributes']['Value']))
                                    {
                                        $release_time = date('Y-m-d',time()).' 00:00:00';
                                    }
                                    elseif(!stripos($v['@attributes']['Value'], '-'))
                                    {
                                        $release_time = $v['@attributes']['Value'].'-1-1 00:00:00';
                                    }
                                    else
                                    {
                                        $release_time = $v['@attributes']['Value'];
                                    }
                                    $vod['release_time'] = $release_time;
                                    $vod['year'] = $v['@attributes']['Value'];
                                    break;
                                case 'Director':
                                    $vod['director'] = str_replace(array(",", " ", "/", "\\", "-", "_",";",'，'), '|', $v['@attributes']['Value']);
                                    break;
                                case 'Actors':
                                    $vod['actor'] = str_replace(array(",", " ", "/", "\\", "-", "_",";",'，'), '|', $v['@attributes']['Value']);
                                    break;
                                case 'Country_of_Origin':
                                    if($v['@attributes']['Value'] === 'NULL' || empty($v['@attributes']['Value']))
                                    {
                                        $vod['national'] = '';
                                    }
                                    else
                                    {
                                        $vod['national'] = $v['@attributes']['Value'];
                                    }
                                    break;
                                case 'Language':
                                    $vod['language'] = empty($v['@attributes']['Value']) ? '' : $v['@attributes']['Value'];
                                    break;
                                case 'TotalNumber':
                                    $vod['totalnum'] = $v['@attributes']['Value'];
                                    break;
                                case 'Summary_Long':
                                    $vod['summary'] = $v['@attributes']['Value'];
                                    break;
                            }
                        }
                    }
                    break;
            }
        }
        foreach ($title as $k=>$value)
        {
            switch ($k)
            {
                case 'AMS':
                    $index['originalid'] = $value['@attributes']['Asset_ID'];
                    $index['name'] = $value['@attributes']['Asset_Name'];
                    break;
                case 'App_Data':
                    if(is_array($value))
                    {
                        foreach ($value as $data)
                        {
                            switch ($data['@attributes']['Name'])
                            {
                                case 'Title':
                                    $index['name'] = str_replace(array('&','\'','\"'), '', $data['@attributes']['Value']);
                                    break;
                                case 'Run_Time':
                                    $index['time_len'] = strtotime($data['@attributes']['Value'])-strtotime(date('Y-m-d'));
                                    break;
                                case 'Show_Type':
                                    $vod['view_type'] = '0';
                                    if(!empty($data['@attributes']['Value']))
                                    {
                                        $vod['assets_category'] =$data['@attributes']['Value'];
                                    }
                                    else
                                    {
                                        $vod['assets_category'] = '电影';
                                    }
                                    foreach ($this->view_type as $key=>$view)
                                    {
                                        if(in_array($data['@attributes']['Value'], $view))
                                        {
                                            $vod['view_type'] = $key;
                                            break;
                                        }
                                    }
                                    break;
                                case 'Chapter':
                                    $chapter = (int)$data['@attributes']['Value'] >= 1 ? $data['@attributes']['Value'] : 1;
                                    $index['index'] = $chapter-1;
                                    break;
                                case 'Summary_Long':
                                    $index['summary'] = $data['@attributes']['Value'];
                                    break;
                                case 'Language':
                                    $index['language'] = empty($data['@attributes']['Value']) ? '' : $data['@attributes']['Value'];
                                    break;
                                case 'Director':
                                    $index['director'] = str_replace(array(",", " ", "/", "\\", "-", "_",";",'，'), '|', $data['@attributes']['Value']);
                                    break;
                                case 'Actors':
                                    $index['actor'] = str_replace(array(",", " ", "/", "\\", "-", "_",";",'，'), '|', $data['@attributes']['Value']);
                                    break;
                                case 'Play_Date':
                                    if(empty($data['@attributes']['Value']))
                                    {
                                        $release_time = date('Y-m-d',time()).' 00:00:00';
                                    }
                                    elseif(!stripos($data['@attributes']['Value'], '-'))
                                    {
                                        $release_time = $data['@attributes']['Value'].'-1-1 00:00:00';
                                    }
                                    else
                                    {
                                        $release_time = $data['@attributes']['Value'];
                                    }
                                    $index['release_time'] = $release_time;
                                    break;
                                case 'Year':
                                    $index['year'] = empty($data['@attributes']['Value']) ? '' : $data['@attributes']['Value'];
                                    break;
                                case 'Country_of_Origin':
                                    if($data['@attributes']['Value'] === 'NULL' || empty($data['@attributes']['Value']))
                                    {
                                        $index['national'] = '';
                                    }
                                    else
                                    {
                                        $index['national'] = $data['@attributes']['Value'];
                                    }
                                    break;
                                case 'OnlineIdentify':
                                    $vod['online_identify'] = $data['@attributes']['Value'];
                                    break;
                                case 'Country_of_Origin':
                                    if($v['@attributes']['Value'] === 'NULL' || empty($v['@attributes']['Value']))
                                    {
                                        $index['national'] = '';
                                    }
                                    else
                                    {
                                        $index['national'] = $v['@attributes']['Value'];
                                    }
                                    break;
                            }
                        }
                    }
                    break;
            }
        }
        $result = array(
            'vod' => $vod,
            'index' => $index
        );
        return $result;
    }

    /**
     * @description:播控注入cdn后统一反馈给二级
     * @author:xinxin.deng
     * @date: 2018/3/2 9:59
     * @param $message_id //消息id
     * @param $code //状态码，失败1，成功0
     * @param $reason //原因描述
     * @param $arr_data //封装好了的反馈信息 array(
     *                                          'cdn_id' => ,注入cdn的id
     *                                          'site_id' => ,配置的站点id
     *                                          'mg_asset_type' => ,注入媒资类型
     *                                          'mg_asset_id' => ,主媒资的消息注入id
     *                                          'mg_part_id' => ,分集的消息注入id
     *                                          'mg_file_id' => ,片源的消息注入id,
     *                                          'is_finally' =>0, 0表示最终状态,反馈的时候将其unset掉
     *                                          );
     * @param $sp_id //sp配置信息
     */
    public function is_ok($message_id, $code, $reason, $arr_data, $sp_id)
    {
        return;
    }
}